package com.noahplat.oauth.config;

import com.noahplat.common.cusexception.UnKnowUserException;
import com.noahplat.oauth.mapper.UserMapper;
import com.noahplat.oauth.utils.UserJwt;
import com.noahplat.user.feign.UserFeign;
import com.noahplat.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 作者：李景星
 * 描述：自定义授权认证类
 * 时间：2020-11-02
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private UserMapper userMapper;

    /**
     * 作者：李景星
     * 描述：自定义授权认证
     * 时间：2020-11-02
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //取出身份，如果身份为空说明没有认证
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
        if(authentication==null){
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
            if(clientDetails!=null){
                //秘钥
                String clientSecret = clientDetails.getClientSecret();
                return new UserJwt(username,clientSecret, AuthorityUtils.commaSeparatedStringToAuthorityList(""));
            }
        }

        if (StringUtils.isEmpty(username)) {
            return null;
        }

        //根据用户名查询用户信息
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username", username);
        User user = userMapper.selectOneByExample(example);
        if(StringUtils.isEmpty(user)){
            throw new BadCredentialsException("该用户不存在");
        }
        //查询权限集合，以字符串的形式传参
        List<String> list = userMapper.getPermisssion(user.getId());
        StringBuffer stringBuffer = new StringBuffer();
        for (String str : list) {
            stringBuffer.append(str).append(",");
        }
        stringBuffer.deleteCharAt(stringBuffer.length()-1);
        String permissions = stringBuffer.toString();
        UserJwt userDetails = new UserJwt(username,user.getPassword(),AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
        userDetails.setId(user.getId());
        userDetails.setName(user.getName());
        userDetails.setUserType(user.getUserType());
        userDetails.setStid(String.valueOf(user.getStid()));
        userDetails.setPid(user.getPid());
        userDetails.setAcctid(user.getAcctid());
        return userDetails;
    }
}
